"""
Main entry point for HeyGen avatar video generator.
Orchestrates the video creation process.
"""

import asyncio
import random
import sys
import os

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.core.browser_manager import BrowserManager
from src.core.login_manager import LoginManager
from src.video_generator.video_creator import VideoCreator
from avatar_data import AVATAR_VOICE_MAP, get_avatar_description


async def search_douyin_videos(keyword, count=50):
    """
    Search Douyin videos by keyword
    """
    from src.video_generator.douyin_video_search import DouyinVideoSearcher
    
    print(f"正在搜索抖音视频: {keyword}，需要获取 {count} 个视频")
    
    # 创建搜索器实例
    searcher = DouyinVideoSearcher()
    
    try:
        # 启动浏览器
        await searcher.start_browser(headless=False)
        
        # 搜索视频
        videos = await searcher.search_videos(keyword, count)
        
        # 输出结果
        print(f"\n成功获取到 {len(videos)} 个视频信息:")
        print("-" * 80)
        for i, video in enumerate(videos, 1):
            print(f"{i}. 视频链接: {video['url']}")
            print(f"   用户名: {video['username']}")
            print(f"   观看数: {video['views']}")
            print()
            
        return videos
    except Exception as e:
        print(f"搜索过程中发生错误: {e}")
        return []
    finally:
        # 关闭浏览器
        await searcher.close()


async def search_videos_by_platform(platform, keyword, count=50):
    """
    Search videos by platform and keyword
    """
    from src.video_generator.video_search_manager import VideoSearchManager
    
    print(f"正在搜索 {platform} 平台视频: {keyword}，需要获取 {count} 个视频")
    
    # 创建搜索管理器实例
    manager = VideoSearchManager()
    
    try:
        # 搜索视频
        videos = await manager.search_videos(platform, keyword, count)
        
        # 输出结果
        print(f"\n成功获取到 {len(videos)} 个视频信息:")
        print("-" * 80)
        for i, video in enumerate(videos, 1):
            print(f"{i}. 视频链接: {video['url']}")
            print(f"   用户名: {video['username']}")
            print(f"   观看数: {video['views']}")
            print()
            
        return videos
    except Exception as e:
        print(f"搜索过程中发生错误: {e}")
        return []


async def search_all_platform_videos(keyword, count_per_platform=50):
    """
    Search videos on all supported platforms
    """
    from src.video_generator.video_search_manager import VideoSearchManager
    
    print(f"正在所有平台搜索视频: {keyword}，每个平台获取 {count_per_platform} 个视频")
    
    # 创建搜索管理器实例
    manager = VideoSearchManager()
    
    try:
        # 搜索所有平台的视频
        results = await manager.search_all_platforms(keyword, count_per_platform)
        
        # 输出结果
        total_count = sum(len(videos) for videos in results.values())
        print(f"\n成功在所有平台获取到 {total_count} 个视频信息:")
        print("-" * 80)
        
        for platform, videos in results.items():
            print(f"\n{platform.upper()} 平台 ({len(videos)} 个视频):")
            print("-" * 80)
            for i, video in enumerate(videos, 1):
                print(f"{i}. 视频链接: {video['url']}")
                print(f"   用户名: {video['username']}")
                print(f"   观看数: {video['views']}")
                print()
            
        return results
    except Exception as e:
        print(f"搜索过程中发生错误: {e}")
        return {}


async def create_batch_avatar_videos():
    """
    Create batch avatar videos - main workflow function.
    """
    # Initialize components
    browser_manager = BrowserManager()
    login_manager = LoginManager("magicbox147@gmail.com", "@Flyingwaves2025")
    video_creator = VideoCreator()
    
    # Start browser
    context, page = await browser_manager.start_browser(headless=False)
    
    try:
        # Navigate to HeyGen
        await browser_manager.navigate_to_heygen()
        
        # Check if already logged in
        if await login_manager.is_logged_in(page):
            print("Already logged in")
        else:
            # Perform login
            if not await login_manager.login(page):
                print("Login failed")
                return
            
        TOTAL_VIDEOS = os.getenv("TOTAL_VIDEOS", 5)
        # Create TOTAL_VIDEOS videos
        avatar_names = list(AVATAR_VOICE_MAP.keys())
        
        for i in range(TOTAL_VIDEOS):
            print(f"\n=== Creating video {i+1}/TOTAL_VIDEOS ===")
            await browser_manager.navigate_to_heygen()
            await page.wait_for_timeout(2000)
            # Randomly select an avatar
            selected_avatar = random.choice(avatar_names)
            avatar_description = get_avatar_description(selected_avatar)
            
            # Create video for selected avatar
            success = await video_creator.create_video(page, selected_avatar, avatar_description)
            
            # If creation failed, skip to next
            if not success:
                print(f"Failed to create video for {selected_avatar}, skipping to next")
                continue
            
            # Wait random time between operations (60 sec +/- 10 sec)
            random_delay = 60 + random.randint(-10, 10)
            print(f"Waiting for {random_delay} seconds before next operation...")
            await page.wait_for_timeout(random_delay * 1000)
            
    finally:
        # Close browser
        await browser_manager.close_browser()
        print("Browser closed")


if __name__ == "__main__":
    asyncio.run(create_batch_avatar_videos())